<?
ini_set(max_execution_time, 200);
//Functions by Rui Torre (http://de3.php.net/manual/de/function.imap-fetchstructure.php)
function decode_headers($cabecalho){
    while (preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?(.*)$/Ui', $cabecalho)){
        $cabecalho = preg_replace("/(\t|\r|\n)/", "", $cabecalho);
        $cabecalho = preg_replace("/\?(Q|B)\?=/Ui", "?\\1? =", $cabecalho);
          
        $partes_cabecalho = explode("?=", $cabecalho);
       
        $resultado = "";
        foreach ($partes_cabecalho as $texto){
            $texto = preg_replace("/\?(Q|B)\?\s=/Ui", "?\\1?=", $texto);
            $texto = preg_replace("/\?(Q|B)\?/Ui", "=?\\1=?", $texto);
           
            if (preg_match('/^(.*)=\?([^?]*)=\?(Q|B)=\?(.*)$/Ui', $texto)){
                $partes_texto = explode ("=?", $texto); 
               
                $parte = descodificar_parte($partes_texto[0], $partes_texto[1]);
                $parte .= descodificar_parte($partes_texto[3], $partes_texto[2]);
            } else {
                $parte = $texto; 
            } 
           
            if (strtoupper($partes_texto[1]) == "UTF-8"){ $parte = utf8_decode($parte);} 
            $resultado .= $parte; 
        }
        $cabecalho = $resultado;
    }
       
    return trim($cabecalho);      
}
function descodificar_parte($texto, $codificacao){
    if (trim($texto) == ""){ return "";}
   
    if (ucfirst($codificacao) == "B"){
        $texto = base64_decode($texto);
        $texto = htmlspecialchars($texto);
    } else if (ucfirst($codificacao) == "Q"){
        $texto = str_replace("_", " ", $texto);
        $texto = quoted_printable_decode($texto); 
    }
    return $texto;
}
//functions from cleong (http://de3.php.net/manual/de/function.imap-fetchbody.php)
function get_mime_type(&$structure) {
    $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
    if($structure->subtype) {
         return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
     }
     return "TEXT/PLAIN";
}

function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) {
    if (!$structure) {
         $structure = imap_fetchstructure($stream, $msg_number);
     }
    if($structure) {
         if($mime_type == get_mime_type($structure)) {
              if(!$part_number) {
                   $part_number = "1";
               }
              $text = imap_fetchbody($stream, $msg_number, $part_number);
              if($structure->encoding == 3) {
                   return imap_base64($text);
               } else if ($structure->encoding == 4) {
                   return imap_qprint($text);
               } else {
                   return $text;
            }
        }
         if ($structure->type == 1) { /* multipart */
              while (list($index, $sub_structure) = each($structure->parts)) {
                if ($part_number) {
                    $prefix = $part_number . '.';
                }
                $data = get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
} 
//Myown functions
function ticketmail($id, $subject, $text){
	//Diese Funktion versendet Mails an alle vom Ticket beteiligte Personen
	$result=$db->query("SELECT DISTINCT Absender FROM support WHERE Id=$id OR Link=$id");
	while($line=$db->fetch_assoc($result)){
		mail($line[Absender],$subject,$text,"FROM:support@mixax.de");
	}
}
if(!isset($_SESSION[support][filter])) $_SESSION[support][filter]=-1;
if($_REQUEST[filter]) $_SESSION[support][filter]=$_REQUEST[filter];
//Neue Nachrichten abfragen
if($_SESSION[mailCheck]<date(U)-200){
	$mbox=imap_open($config[support][server], $config[support][user], $config[support][passwort]);
	$header=imap_check($mbox);
}
if($header->Nmsgs>0) //Es gibt Nachrichten
{
    $content=imap_fetch_overview($mbox,"1:".$header->Nmsgs,0);
	foreach($content as $value)		
    {	
        $header=imap_headerinfo($mbox,$value->uid,1);
		$subject=decode_headers($value->subject);
		$body=get_part($mbox, $value->uid, "TEXT/PLAIN");
		$from=$header->from[0]->mailbox."@".$header->from[0]->host;
		$time=intval($header->udate);
        $body=strip_tags(imap_utf8($body));
		//gucken ob es ein neuer Vorgang ist oder ein alter
		if(ereg("Case #(.*):",$subject,$case)){
		    $case=$case[1];
		}else{
			$new=true;
		}
		if($new==false){
		    $db->query("SELECT * FROM support WHERE Id=".intval($case));
			if($ticket=$db->fetch_assoc()){
				$fp=fopen("data/tickets/ticket-$ticket[Id].txt", a);
				fputs($fp,"--------------------------------------------------\n");
				fputs($fp,"--->User ($from) answered \nDate: ".date("d.m.Y H:i:s",$time)." after ".showtime($time-$ticket[Zeit])."\n");
				fputs($fp,"\n\n".$body."\n\n");
				fputs($fp,"\nTimer has been stopped and restarted for Support \n");
				fclose($fp);
				$db->query("UPDATE support SET WaitFor=Bearbeiter, Zeit=".$time." WHERE Id=$ticket[Id]");	
				if($ticket[Typ]==10){
				    $db->query("UPDATE support SET Typ=1 WHERE Id=$ticket[Id]");
				}
			}else{
				$new=true;
			}
		}
		if($new==true){
			$query="INSERT INTO support(Subject,Typ,Absender,Prio,Zeit) VALUES('".$db->real_escape_string($subject)."',0,'".$db->real_escape_string($from)."',3,".$time.")";
			$db->query($query);
			$db->query("SELECT MAX(Id) AS Id FROM support;");
			$id=$db->result(0,"Id"); 
			$fp=fopen("data/tickets/ticket-$id.txt","w");
			fputs($fp,"---Ticket fetched at ".date("d.m.Y H:i:s",$time)." by System---\n\n");
			fputs($fp,$body);
			fclose($fp);
		}
		//nachricht zum löschen markieren (damit die nicht noch mal gelesen wird)
	    imap_delete($mbox,$value->uid);
	}
	//markierte nachrichten löschen
	imap_expunge($mbox);
}

//Eigentliches Supportsystem

if(isset($_REQUEST[eraseticket])){
	//datenbankeintrag löschen
	$db->query("DELETE FROM support WHERE Id=".intval($_REQUEST[eraseticket])." and Bearbeiter=".$_SESSION[user][Id]) ;
	//logdatei löschen
	if($db->affected_rows()>0){
		unlink("data/tickets/ticket-$_REQUEST[eraseticket].txt");
	}
}
if(!isset($_REQUEST[ticket])){
	?>
	<link href="templates/default/css/forum.css" rel="stylesheet" type="text/css">
	<h2>Meldungen in deinem Pool</h2>
	<table class="forum">
	  <tr class="forum_kat">
        <th>Betreff</th>
	    <th>Requester</th>
	    <th>
		  <select onchange="location.href='index.php?page=admin&adminpage=support&filter='+this.value;">
		    <option value="-1">Alle Anzeigen</option>
			<?
			foreach($config[support][typ] as $key=>$value){
				if($_SESSION[support][filter]==$key) 
					echo "<option value=\"$key\" selected=\"selected\">$value</option>";
				else
					echo "<option value=\"$key\">$value</option>";
			}
			?>			
		</th>
		<th>Zeit</th>
      </th>
      <?
	  if(intval($_SESSION[support][filter])>=0) $filter="AND Typ=".intval($_SESSION[support][filter]);
	  else $filter="AND Typ!=10";
	  echo "SELECT * FROM support WHERE Bearbeiter='' $filter ORDER BY Prio ASC, Zeit ASC";
      $result=$db->query("SELECT * FROM support WHERE Bearbeiter='' $filter ORDER BY Prio ASC, Zeit ASC;");
      while($line=$db->fetch_assoc())
      {
	      echo "
	      <tr bgcolor=\"".$config[support][prio][$line[Prio]]."\" onclick=\"location.href='index.php?page=$_SESSION[page]&adminpage=$_SESSION[adminpage]&ticket=$line[Id]';\">
	        <td>$line[Subject]</td>
	        <td>$line[Absender]</td>
	        <td>".$config[support][typ][$line[Typ]]."</td>
            <td>".date("d.m.Y H:i:s",$line[Zeit])."</td>
	      <tr>";
      }
      ?>
    </table>
	<h2>Von dir in Bearbeitung:</h2>
	<table class="forum">
	  <tr class="forum_kat">
        <th>Betreff</th>
	    <th>Requester</th>
	    <th>Typ</th>
		<th>Time</th>
      </th>
      <?
      $result=$db->query("SELECT * FROM support WHERE Bearbeiter='".$_SESSION[user][Id]."' AND  Link=0 ORDER BY Prio ASC, Zeit ASC;");
      while($line=$db->fetch_assoc($result))
      {
		  if($line[WaitFor]==$_SESSION[user][Id]){
			  $brief="<img src=\"images/letter_ani.gif\" height=\"13px\" alt=\"sollte dringend bearbeitet werden\">";
		  }else{
			  $brief="";
		  }
		  
	      echo "
	      <tr bgcolor=\"".$config[support][prio][$line[Prio]]."\" onclick=\"location.href='index.php?page=$_SESSION[page]&adminpage=$_SESSION[adminpage]&ticket=$line[Id]';\">
	        <td>$line[Subject]</td>
	        <td>".substr($line[Absender],0,25)."</td>
	        <td>".$config[support][typ][$line[Typ]]."</td>
			<td>$brief".showtime(date(U)-$line[Zeit])."</td>
	      <tr>";
		}
      echo "
    </table>";

}else{
    $db->query("SELECT * FROM support WHERE Id=".intval($_REQUEST[ticket]));
	if($ticket=$db->fetch_assoc()){
		$path="data/tickets/ticket-$ticket[Id].txt";
		//DOs bearbeiten
		if(strlen($_REQUEST[changetopic])>5){
			$ticket[Subject]=$db->real_escape_string($_REQUEST[changetopic]);
			$db->query("UPDATE support SET Subject='$ticket[Subject]' WHERE Id=$ticket[Id]");
		}
		if($_REQUEST['do']=="take")
		{
			if($ticket[Bearbeiter]!=0){
				echo "<div class=\"error\">Das Ticket wurde bereits von einem anderen Übernommen</div>";
			}else{
				$fp=fopen($path, a);
				fputs($fp,"--------------------------------------------------\n");
				fputs($fp,"--->Ticket assigned to ".$_SESSION[user][Name]." \nDate: ".date("d.m.Y H:i:s")." after ".showtime(date(U)-$ticket[Zeit])."\n");
				fputs($fp,"Timer has been stopped and restarted for ".$_SESSION[user][Name]."\n");
				fclose($fp);
				$db->query("UPDATE support SET Typ=1 WHERE Typ=0 AND Id=$ticket[Id]");
				$db->query("UPDATE support SET WaitFor=".$_SESSION[user][Id].", Bearbeiter=".$_SESSION[user][Id].", Zeit=".date(U)." WHERE Id=$ticket[Id]");
				$ticket[Bearbeiter]=$_SESSION[user][Id];
				$ticket[Zeit]=date(U);
			}
		}
		if($_REQUEST['do']=="answer")
		{
			$subject="Case #$ticket[Id]: $ticket[Subject]";
			$mail=$_REQUEST[answer];
			$mail.="\n\n---------------------------------------------------";
			$mail.="\nBTS-Ticket-System.";
			$mail.="\nBitte den Betreff NICHT verändern, damit dir schnell geholfen werden kann.";
			$mail.="\nDen aktuellen Status deines Tickets kannst du unter http://www.mixax.de/data/tickets/ticket-$ticket[Id].txt nachlesen.";
 		    $fp=fopen($path, a);
			fputs($fp,"--------------------------------------------------\n");
			if(isset($_REQUEST[sendmail])){
			    fputs($fp,"--->Ticket answered by ".$_SESSION[user][Name]." \nDate: ".date("d.m.Y H:i:s")." after ".showtime(date(U)-$ticket[Zeit])."\n");
		    }else{
			    fputs($fp,"--->Ticket commented by ".$_SESSION[user][Name]);
			}
			fputs($fp,"\n".$_REQUEST[answer]."\n");
			if(isset($_REQUEST[sendmail]))
			    fputs($fp,"\nTimer has been stopped and restarted for User \n");
			fclose($fp);
			if(isset($_REQUEST[sendmail])){
			    $db->query("UPDATE support SET WaitFor=0, Zeit=".date(U)." WHERE Id=$ticket[Id]");
			    $ticket[Zeit]=date(U);
			    $ticket[WaitFor]=0;
			    ticketmail($ticket[Id],$subject,$mail);
			}
		}
		if(isset($_REQUEST['addto']))
		{
			$addto=intval($_REQUEST[addto]);
			$subject="Case #$ticket[Id]: $ticket[Subject]";
			$mail="Hallo\n";
			$mail.="Dein Ticket wurde von ".$_SESSION[user][Name]." mit einem anderen Ticket zusammengeführt.\n";
			$mail.="Mehr Informationen zu dem Ticket gibt es unter http: http://www.mixax.de/data/tickets/ticket-$addto.txt";
 		    $fp=fopen($path, a);
			fputs($fp,"--------------------------------------------------\n");
			fputs($fp,"--->Ticket linked to Ticket #$addto by ".$_SESSION[user][Name]." \nDate: ".date("d.m.Y H:i:s")." after ".showtime(date(U)-$ticket[Zeit])."\n");
			fclose($fp);
			$db->query("UPDATE support SET Link=$addto WHERE Id=$ticket[Id]");
			$ticket[Zeit]=date(U);
			$ticket[Link]=$addto;
			ticketmail($ticket[Id],$subject,$mail);
		}

		if(isset($_REQUEST['eskalieren']))
		{
 		    $fp=fopen($path, a);
			fputs($fp,"--------------------------------------------------\n");
			fputs($fp,"--->Ticket eskalated by ".$_SESSION[user][Name]." to ".$config[support][typ][intval($_REQUEST['eskalieren'])]." \nDate: ".date("d.m.Y H:i:s")." after ".showtime(date(U)-$ticket[Zeit])."\n");
			fclose($fp);
			$db->query("UPDATE support SET WaitFor=0, Bearbeiter=0, Typ=".intval($_REQUEST['eskalieren']).", Zeit=".date(U)." WHERE Id=$ticket[Id]");
			$ticket[Zeit]=date(U);
			$ticket[Link]=$addto;
			$ticket[Bearbeiter]=0;
		}
		if(isset($_REQUEST['changeprio']))
		{
			$ticket[Prio]=intval($_REQUEST[changeprio]);
 		    $fp=fopen($path, a);
			fputs($fp,"--------------------------------------------------\n");
			fputs($fp,"--->Ticket got higher priority ($ticket[Prio])by ".$_SESSION[user][Name]." \nDate: ".date("d.m.Y H:i:s")." after ".showtime(date(U)-$ticket[Zeit])."\n");
			fclose($fp);
			$db->query("UPDATE support SET Prio=$ticket[Prio] WHERE Id=$ticket[Id]");
		}

		echo "
		<center>
	      <a href=\"index.php?page=$_SESSION[page]&adminpage=$_SESSION[adminpage]\"><b>Hier gehts zurück zur Übersicht</b></a>
		</center>
		<table bgcolor=\"".$config[support][prio][$ticket[Prio]]."\">
		<tr>
		  <th>Subject:</th>
		  <th>$ticket[Subject]</th>
	    </tr>
	    <tr>
		  <th>Requester:</th>
		  <th><pre>";
			$result=$db->query("SELECT * FROM support WHERE Id=$ticket[Id] OR Link=$ticket[Id]");
			while($line=$db->fetch_assoc()){
				echo "$line[Absender];";
			}
			echo"
			</pre>
		  </th>
	    </tr>";
        if($ticket[Bearbeiter]==$_SESSION[user][Id]){
		    echo "
		    <tr>
		      <th colspan=\"2\" align=\"center\">";
			    if($ticket[WaitFor]==0){
					echo "Warte auf Rückmeldung vom User";
				}else{
					echo "Das Ticket wird momentan bei dir bearbeitet";
				}
				echo " (".showtime(date(U)-$ticket[Zeit]).")
			  </th>
		    </tr>";
	    }
        if($ticket[Bearbeiter]==0){
		    echo "
		    <tr>
		      <th colspan=\"2\" align=\"center\">
	  	  	    <input type=\"button\" value=\"Dieses Ticket in meinen Pool übernehmen\" onclick=\"location.href='index.php?page=$_SESSION[page]&adminpage=$_SESSION[adminpage]&ticket=$_REQUEST[ticket]&do=take';\" />
			  </th>
		    </tr>";
	    }		
	    echo "
	    <tr>
	      <th colspan=\"2\">
		    <textarea readonly=\"readonly\" rows=\"25\" cols=\"88\">".file_get_contents("data/tickets/ticket-$ticket[Id].txt")."</textarea>
		  </th>
	    </tr>
	  </table>";
      //Antwortfeld generieren
      if($ticket[Bearbeiter]==$_SESSION[user][Id] AND $ticket[Link]==0){
		  echo "
		  <h2>Antwort schreiben</h2>
		  <form action=\"index.php\" method=\"post\">
		    <input type=\"hidden\" name=\"page\" value=\"$_SESSION[page]\" />
		    <input type=\"hidden\" name=\"adminpage\" value=\"$_SESSION[adminpage]\" />
		    <input type=\"hidden\" name=\"ticket\" value=\"$ticket[Id]\" />
		    <input type=\"hidden\" name=\"do\" value=\"answer\" />			
			<input type=\"checkbox\" name=\"sendmail\" checked=\"checked\">
			<b>Antwort an Requester senden:</b>
			<textarea name=\"answer\" rows=\"7\" cols=\"88\"></textarea><br>
			<input type=\"submit\" value=\"absenden\" />
		  </form>";
	  }
      if($ticket[Bearbeiter]==$_SESSION[user][Id] AND $ticket[Link]==0){
		  echo "
		  <h2>Weitere Optionen:</h2>
		  <table>
		    <tr>
			  <td>
				<form action=\"index.php\" method=\"post\">
		          <input type=\"hidden\" name=\"page\" value=\"$_SESSION[page]\" />
		          <input type=\"hidden\" name=\"adminpage\" value=\"$_SESSION[adminpage]\" />
		          <input type=\"hidden\" name=\"ticket\" value=\"$ticket[Id]\" />				  
			      <select name=\"eskalieren\">";
					foreach($config[support][typ] as $id=>$name){
						if($ticket[Typ]==$id){
							echo "<option value=\"$id\" selected=\"selected\">$name</option>";
						}else{
							echo "<option value=\"$id\">$name</option>";
						}
					} 
					echo "				  
			      </select>
				  <input type=\"submit\" value=\"<-eskalieren\" />
				</form>
			  </td>
			  <td>
			    <input type=\"button\" value=\"Ticket löschen\" onclick=\"if(confirm('Tickets sollten nur gelöscht werden, wenn sie absolut sinnfrei sind. Ansonsten wird ein Ticket geschlossen (eskalieren gegen close)')) location.href='index.php?page=$_SESSION[page]&adminpage=$_SESSION[adminpage]&eraseticket=$ticket[Id]';\"/>
			  </td>
			  <td>
			    <input type=\"button\" value=\"Subject ändern\" onclick=\"location.href='index.php?page=$_SESSION[page]&adminpage=$_SESSION[adminpage]&ticket=$ticket[Id]&changetopic='+prompt('Neuer ausagekräftiger Titel für das Ticket:','');\"/>
			  </td>
			  <td>
			    <input type=\"checkbox\" /><b>public</b>
			  </td>
			</tr>
			<tr>
			  <td colspan=\"2\">
				<b>Anhängen an das Ticket:
				<form action=\"index.php\" method=\"post\">
		          <input type=\"hidden\" name=\"page\" value=\"$_SESSION[page]\" />
		          <input type=\"hidden\" name=\"adminpage\" value=\"$_SESSION[adminpage]\" />
		          <input type=\"hidden\" name=\"ticket\" value=\"$ticket[Id]\" />				  
			      <select name=\"addto\">
				    <option value=\"0\">Bitte Ticket auswählen</option>";
				    $result=$db->query("SELECT * FROM support WHERE Bearbeiter=".$_SESSION[user][Id]." AND Link=0 AND Id!=$ticket[Id]");
				    while($line=$db->fetch_assoc()){
					    echo "<option value=\"$line[Id]\">$line[Subject]</option>";
				    }
				    echo "
				  </select>
				  <input type=\"submit\" value=\"anhängen\" />
				</form>
			  </td>
			  <td colspan=\"2\">
				<b>Prio:
				<form action=\"index.php\" method=\"post\">
		          <input type=\"hidden\" name=\"page\" value=\"$_SESSION[page]\" />
		          <input type=\"hidden\" name=\"adminpage\" value=\"$_SESSION[adminpage]\" />
		          <input type=\"hidden\" name=\"ticket\" value=\"$ticket[Id]\" />				  
			      <select name=\"changeprio\">";
				    foreach($config[support][prio] AS $key=>$value){
					    if($ticket[Prio]==$key){
							echo "
							<option value=\"$key\" selected=\"selected\">$key</option>";
						}else{
							echo "
						    <option value=\"$key\">$key</option>";
						}
					}
				    echo "
				  </select>
				  <input type=\"submit\" value=\"ok\" />
				</form>
			  </td>

			  
			</tr>
		  </table>";
	  }
	  
    }
}  